//
//  ChangeLinkResultVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/9/15.
//

import UIKit

class ChangeLinkResultVC: ZMViewController {

    // MARK: - UI
    // 状态
    @IBOutlet weak var stateImg: UIImageView!
    @IBOutlet weak var state: UILabel!
    // 清空
    @IBOutlet weak var clearView: UIStackView!
    // 内容
    @IBOutlet weak var textView: UITextView!
    // 成功提示
    @IBOutlet weak var tipView: UIStackView!
    @IBOutlet weak var tip: UILabel!
    // 重新转换
    @IBOutlet weak var resetBtn: UIButton!
    // 复制
    @IBOutlet weak var copyBtn: UIButton!
    // 成功商品
    @IBOutlet weak var resultView: UIView!
    @IBOutlet weak var resultList: UITableView!
    @IBOutlet weak var resultHeight: NSLayoutConstraint!
    
    var info: ChangeLinkModel?
    var sucNum = 0
    var errNum = 0
    var textStr = ""
    var clearBlock: (()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "转链"
        view.backgroundColor = "#F5F5F5".zm.hex()
        requestLink()
//        setUI()
        setTable()
        bindAction()
    }

    func setUI() {
        
        if let jb = info?.jdLink {
            sucNum += 1
        } else {
            errNum += 1
        }
        if let tb = info?.tbGoods {
//            textStr = tb.shortUrl
            sucNum += 1
        } else {
            errNum += 1
        }
        if sucNum == 0 {
            state.text = "转链失败"
            stateImg.image = UIImage(named: "change_link_8")
            copyBtn.isUserInteractionEnabled = false
            copyBtn.backgroundColor = "#CCCCCC".zm.hex()
            resultView.isHidden = true
        } else {
            stateImg.image = UIImage(named: "change_link_7")
            state.text = "转链成功"
            copyBtn.isUserInteractionEnabled = true
            copyBtn.backgroundColor = "#DE3F26".zm.hex()
            resultView.isHidden = false
            resultList.reloadData()
        }
        
        textView.text = textStr
        let tipStr = "转链成功\(sucNum)条，失败\(errNum)条"
        let attrString = NSMutableAttributedString(string: tipStr)
        attrString.addAttributes([.foregroundColor: "#DE3F26".zm.hex()], range: NSRange(location: 3, length: "\(sucNum)".count))
        attrString.addAttributes([.foregroundColor: "#DE3F26".zm.hex()], range: NSRange(location: 7+"\(errNum)".count, length: "\(errNum)".count))
        tip.attributedText = attrString

//        let attrString = NSMutableAttributedString(string: tipStr)
//        attrString.addAttributes([.foregroundColor: "#DE3F26".zm.hex()], range: NSRange(tipStr.range(of: "成功")!,in:tipStr))
//        attrString.addAttributes([.foregroundColor: "#DE3F26".zm.hex()], range: NSRange(tipStr.range(of: "失败")!,in:tipStr))
//        tip.attributedText = attrString
    }
    
    func setTable() {
        resultList.register(UINib(nibName: "ChangeLinkResultCell", bundle: nil), forCellReuseIdentifier: "ChangeLinkResultCell")
        resultList.rowHeight = UITableView.automaticDimension
        resultList.estimatedRowHeight = 44
        resultList.delegate = self
        resultList.dataSource = self
        resultList.separatorStyle = .none
        resultList.tableFooterView = UIView()
    }

    // MARK: - bindAction
    func bindAction() {
        let clearTap = UITapGestureRecognizer()
        clearView.addGestureRecognizer(clearTap)
        clearTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            if let block = self.clearBlock {
                block()
            }
            self.navigationController?.popViewController(animated: true)
        }).disposed(by: disposeBag)
        
        resultList.rx.observeWeakly(CGSize.self, "contentSize").subscribe(onNext: { [unowned self] (change) in
            self.resultHeight.constant = change!.height
        }).disposed(by: disposeBag)
        
        resetBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.navigationController?.popViewController(animated: true)
        }).disposed(by: disposeBag)
        
        copyBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            UIPasteboard.general.string = self.textStr
            ZMToast.showToast(title: "复制成功")
        }).disposed(by: disposeBag)
    }
}

extension ChangeLinkResultVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sucNum
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ChangeLinkResultCell", for: indexPath) as! ChangeLinkResultCell
//        if let tb = info?.tbLink {
//            cell.setUI(tb)
//        }
        return cell
    }
}

// MARK: - Request Action
extension ChangeLinkResultVC {
    func requestLink() {
        guard let txt = textView.text, txt != "" else {
            return
        }
        ZMToast.showActivity()
        HomeAPI.change_link(txt).rxRequestNullAble(type: ChangeLinkModel.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            let vc = ChangeLinkResultVC()
            if let data = resp {
                vc.info = data
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }).disposed(by: disposeBag)
    }
}
